layui.use(['element', "layer", "upload", "flow"], function () {
    const element = layui.element,
        layer = layui.layer,
        upload = layui.upload,
        flow = layui.flow;
    var Viewer = window.Viewer;

    // 渲染组件
    element.init();

    // 退出
    $("#logout").bind("click", function () {
        layer.load(2);
        layer.confirm('确定要退出登录？', {
            btn: ['确认', '返回'], //按钮
            title: "提示"
        }, function () {
            $.post("logout", {}, function (data, status) {
                if (data.code === 1) {
                    // 登出成功
                    layer.msg('退出成功', {icon: 1, time: 1000}, function () {
                        location.replace("/login");
                    });
                }
            });
        }, function () {
            layer.closeAll('loading');
        });
    });

    // 上传框
    $("#upload").bind("click", function () {
        $("#imgList").html("");
        // 弹出页面
        layer.open({
            type: 1,
            title: '上传图片',
            area: ['50%', '50%'],
            shade: 0,
            offset: 'auto',
            content: $("#uploadDiv"),
            btn: ['关闭'],
            yes: function () {
                layer.closeAll();
            },
            success: function () {
                fileListView.html("");
            }
        });
    });

    // 上传绑定
    let fileListView = $("#fileList");
    let imgUpload = upload.render({
        elem: '#uploadListBut',
        url: '/upload/img',
        accept: 'images',
        acceptMime: 'image/*',
        auto: false,                // 是否自动上传
        bindAction: '#uploadAction',   // 上传按钮绑定
        multiple: true,
        choose: function (obj) {
            var files = this.files = obj.pushFile(); //将每次选择的文件追加到文件队列
            //读取本地文件
            obj.preview(function (index, file, result) {
                var tr = $(['<tr id="upload-' + index + '">'
                    , '<td>' + file.name + '</td>'
                    , '<td>' + (file.size / 1024).toFixed(1) + 'kb</td>'
                    , '<td>等待上传</td>'
                    , '<td>'
                    , '<button class="layui-btn layui-btn-xs list-item-reload layui-hide">重传</button>'
                    , '<button class="layui-btn layui-btn-xs layui-btn-danger list-item-delete">删除</button>'
                    , '</td>'
                    , '</tr>'].join(''));

                //单个重传
                tr.find('.list-item-reload').on('click', function () {
                    obj.upload(index, file);
                });

                //删除
                tr.find('.list-item-delete').on('click', function () {
                    delete files[index]; //删除对应的文件
                    tr.remove();
                    imgUpload.config.elem.next()[0].value = ''; //清空 input file 值，以免删除后出现同名文件不可选
                });
                fileListView.append(tr);
            });
        }, done: function (res, index, upload) {
            if (res.code === 1) { //上传成功
                var tr = fileListView.find('tr#upload-' + index), tds = tr.children();
                tds.eq(2).html('<span style="color: #5FB878;">上传成功</span>');
                tds.eq(3).html(''); //清空操作
                return delete this.files[index]; //删除文件队列已经上传成功的文件
            } else {
                this.error(index, upload);
            }
        }, error: function (index, upload) {
            var tr = fileListView.find('tr#upload-' + index), tds = tr.children();
            tds.eq(2).html('<span style="color: #FF5722;">上传失败</span>');
            tds.eq(3).find('.list-item-reload').removeClass('layui-hide'); //显示重传
        }, allDone: function (obj) {
            // 当文件全部提交后才触发
            if (obj.total === obj.successful) {
                // 成功文件 等于 提交文件 关闭弹框
                layer.msg('所有图片已上传成功, 即将关闭上传框', {
                    icon: 1,
                    time: 2000
                }, function () {
                    layer.closeAll();
                    // 刷新页面
                    reloadFlow();
                });
            }
        }
    });

    // 获取当前窗口高度
    let windowHeight = $(window).height() - 15 * 2;
    let windowWidth = $(window).width() - 15 * 2;
    let imgDivH = 180 + 10 * 2 + 15 * 2;
    let imgDivW = 180 + 10 * 2 + 15 * 2;
    // 通过窗口计算每页的展示数量 (假设一行即为一页, 初始加载时加载 N 页)
    let rowImgs = Math.floor(windowWidth / imgDivW);
    let rows = Math.floor(windowHeight / imgDivH);

    /**
     * 初始化流加载
     */
    let isFastInit = true;

    function initFlow() {
        var options = {
            elem: "#img-panel-list",
            isLazyimg: true,
            mb: 150,
            done: function (page, next) {
                var listView = [];
                var size = rowImgs;
                if (isFastInit) {
                    size = rowImgs * rows;
                    isFastInit = false;
                } else {
                    page = rows + 1;
                    size = rowImgs;
                }
                //执行下一页的回调
                $.post("/file/getList", {
                    current: page,
                    size: size
                }, function (res) {
                    if (res.code !== 1) {
                        layer.msg("加载失败...");
                    } else {
                        var items = res.data;
                        var imgs = items.records;
                        let ids = [];
                        for (var i = 0; i < imgs.length; i++) {
                            let id = "img_" + imgs[i].id;
                            ids.push(id);
                            var li = ['<li style="display: inline-block;">',
                                '<div class="layui-panel img-panel">',
                                '<img class="img-item" data-original="' + imgs[i].accessPath + '" alt="' + imgs[i].fileName + '" lay-src="' + imgs[i].accessPath + '"/>',
                                '<div class="img-operate">',
                                '<button type="button" class="layui-btn layui-btn-normal layui-btn-sm img-item-delete" id="' + id + '"><i class="layui-icon"></i></button>',
                                '</div>',
                                '</div>',
                                '</li>'].join("");

                            listView.push(li);
                        }
                        next(listView.join(''), page < items.pages);
                        // 更新图片查看器
                        viewer.update();
                        // 绑定删除事件
                        for (let i = 0; i < ids.length; i++) {
                            $("#" + ids[i]).on("click", function () {
                                var imgId = ids[i].substr(ids[i].indexOf("_") + 1, ids.length + 1);
                                delImg(imgId);
                            });
                        }
                    }
                });
            }
        };
        flow.load(options);
    }

    /**
     * 重载方法
     */
    function reloadFlow() {
        var index = layer.load(2);
        // 移除元素
        $("#img-panel-list").remove();
        // 重新生成元素
        $("#img-panel-list-parent").html('<ul id="img-panel-list"></ul>');
        // 重新初始化
        isFastInit = true;
        // 绑定并初始化
        initFlow();
        // 重新绑定图片查看器
        initViewer();
        layer.close(index);
    }

    /**
     * 初始化图片查看器
     */
    var viewer;

    function initViewer() {

        viewer = new Viewer(document.getElementById('img-panel-list'), {
            url: "data-original"
        });
    }

    /**
     * 删除
     * @param id
     */
    function delImg(id) {
        layer.load(2);
        layer.confirm('确定要删除此图片？', {
            btn: ['确认', '返回'], //按钮
            title: "提示"
        }, function () {
            $.post("/file/del", {id: id}, function (res) {
                if (res.code === 1) {
                    layer.msg(res.message, {
                        icon: 1,
                        time: 500
                    }, function () {
                        // 刷新页面
                        reloadFlow();
                    });
                } else {
                    layer.msg(res.message);
                }
            });
        }, function () {
            layer.closeAll('loading');
        });
    }

    // 流加载
    initFlow();
    // 图片查看器加载
    initViewer();
});